import React, { useState, useEffect, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { CartItem } from './types/product';
import './OrderConfirm.css';
import Layout from './Layout';

const OrderConfirm = () => {
    const navigate = useNavigate();
    const [orderItems, setOrderItems] = useState<CartItem[]>([]);
    const [address, setAddress] = useState({
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detail: ''
    });

    useEffect(() => {
        // 从localStorage获取订单数据
        const items = JSON.parse(localStorage.getItem('currentOrder') || '[]');
        setOrderItems(items);
    }, []);

    const handleAddressChange = (field: keyof typeof address, value: string) => {
        setAddress(prev => ({
            ...prev,
            [field]: value
        }));
    };

    const calculateTotal = useMemo(() => {
        return orderItems.reduce((total, item) => {
            let itemTotal = item.price * item.quantity;

            // 添加服务费用
            if (item.selectedServices && item.selectedServices.length > 0) {
                item.selectedServices.forEach(serviceId => {
                    const service = item.services.find(s => s.id === serviceId);
                    if (service) {
                        itemTotal += service.price * item.quantity;
                    }
                });
            }

            // 添加配件费用
            if (item.selectedAccessories && item.selectedAccessories.length > 0) {
                item.selectedAccessories.forEach(accessoryId => {
                    const accessory = item.accessories.find(a => a.id === accessoryId);
                    if (accessory) {
                        itemTotal += accessory.price * item.quantity;
                    }
                });
            }

            return total + itemTotal;
        }, 0);
    }, [orderItems]);

    const handleSubmitOrder = () => {
        // 验证地址信息
        if (!address.name || !address.phone || !address.province ||
            !address.city || !address.district || !address.detail) {
            alert('请填写完整的收货信息');
            return;
        }

        // 创建订单对象
        const order = {
            id: Date.now().toString(),
            items: orderItems,
            address,
            total: calculateTotal,
            status: '待付款',
            createTime: new Date().toISOString()
        };

        // 保存订单
        const orders = JSON.parse(localStorage.getItem('orders') || '[]');
        orders.push(order);
        localStorage.setItem('orders', JSON.stringify(orders));
        sessionStorage.setItem('orders', JSON.stringify(orders));

        // 保存当前订单ID到sessionStorage，用于支付成功后更新状态
        sessionStorage.setItem('currentOrderId', order.id);

        // 清除当前订单
        localStorage.removeItem('currentOrder');

        // 跳转到支付页面
        navigate('/payment');
    };

    if (orderItems.length === 0) {
        return (
            <div className="order-empty">
                <h2>订单信息不存在</h2>
                <button onClick={() => navigate('/productDetail')}>返回首页</button>
            </div>
        );
    }

    return (
        <Layout>
            <div className="order-confirm">
                <h2>确认订单</h2>

                <div className="address-section">
                    <h3>收货地址</h3>
                    <div className="address-form">
                        <input
                            type="text"
                            placeholder="收货人姓名"
                            value={address.name}
                            onChange={e => handleAddressChange('name', e.target.value)}
                        />
                        <input
                            type="text"
                            placeholder="手机号码"
                            value={address.phone}
                            onChange={e => handleAddressChange('phone', e.target.value)}
                        />
                        <div className="address-location">
                            <input
                                type="text"
                                placeholder="省份"
                                value={address.province}
                                onChange={e => handleAddressChange('province', e.target.value)}
                            />
                            <input
                                type="text"
                                placeholder="城市"
                                value={address.city}
                                onChange={e => handleAddressChange('city', e.target.value)}
                            />
                            <input
                                type="text"
                                placeholder="区/县"
                                value={address.district}
                                onChange={e => handleAddressChange('district', e.target.value)}
                            />
                        </div>
                        <input
                            type="text"
                            placeholder="详细地址"
                            value={address.detail}
                            onChange={e => handleAddressChange('detail', e.target.value)}
                        />
                    </div>
                </div>

                <div className="order-items">
                    <h3>商品信息</h3>
                    {orderItems.map(item => (
                        <div key={item.id} className="order-item">
                            <img src={item.images[0]} alt={item.name} className="item-image" />
                            <div className="item-info">
                                <h4>{item.name}</h4>
                                <p className="specs">
                                    {item.selectedSpecs.color && `颜色：${item.selectedSpecs.color}`}
                                    {item.selectedSpecs.storage && ` 存储：${item.selectedSpecs.storage}`}
                                </p>
                                <div className="services">
                                    {item.selectedServices && item.selectedServices.map(serviceId => {
                                        const service = item.services.find(s => s.id === serviceId);
                                        return service && (
                                            <span key={service.id} className="service-tag">
                                                {service.name} (+¥{service.price})
                                            </span>
                                        );
                                    })}
                                </div>
                                <div className="accessories">
                                    {item.selectedAccessories && item.selectedAccessories.map(accessoryId => {
                                        const accessory = item.accessories.find(a => a.id === accessoryId);
                                        return accessory && (
                                            <span key={accessory.id} className="accessory-tag">
                                                {accessory.name} (+¥{accessory.price})
                                            </span>
                                        );
                                    })}
                                </div>
                            </div>
                            <div className="item-price">¥{item.price}</div>
                            <div className="item-quantity">x{item.quantity}</div>
                            <div className="item-total">
                                ¥{(item.price +
                                    (item.selectedServices?.reduce((sum, serviceId) => {
                                        const service = item.services.find(s => s.id === serviceId);
                                        return sum + (service?.price || 0);
                                    }, 0) || 0) +
                                    (item.selectedAccessories?.reduce((sum, accessoryId) => {
                                        const accessory = item.accessories.find(a => a.id === accessoryId);
                                        return sum + (accessory?.price || 0);
                                    }, 0) || 0)
                                ) * item.quantity}
                            </div>
                        </div>
                    ))}
                </div>

                <div className="order-summary">
                    <div className="total">
                        总计：¥{calculateTotal}
                    </div>
                    <button
                        className="submit-order-btn"
                        onClick={handleSubmitOrder}
                    >
                        提交订单
                    </button>
                </div>
            </div>
        </Layout>
    );
};

export default OrderConfirm; 